import 'package:dio/dio.dart';

class NetException implements Exception {
  final String msg;
  final int code;
  NetException(this.code, this.msg);

  @override
  String toString() {
    return '$code--$msg';
  }

  factory NetException.create(DioError error) {
    switch (error.type) {
      case DioErrorType.cancel:
        return BadRequestException(-1, '请求取消');
      case DioErrorType.connectTimeout:
        return BadRequestException(-1, '连接超时');
      case DioErrorType.sendTimeout:
        return BadRequestException(-1, '请求超时');
      case DioErrorType.receiveTimeout:
        return BadRequestException(-1, '响应超时');
      case DioErrorType.response:
        int? errCode = error.response?.statusCode;
        if (errCode == null) {
          return NetException(-1, '未知错误');
        }
        switch (errCode) {
          case 400:
            return BadRequestException(errCode, '请求语法错误');
          case 401:
            return BadRequestException(errCode, '没有权限');
          case 403:
            return BadRequestException(errCode, '服务器拒绝执行');
          case 404:
            return BadRequestException(errCode, '无法连接服务器');
          case 405:
            return BadRequestException(errCode, '请求方法被禁止');
          case 500:
            return BadRequestException(errCode, '服务器内部错误');
          case 502:
            return BadRequestException(errCode, '无效的请求');
          case 503:
            return BadRequestException(errCode, '服务器挂了');
          case 504:
            return BadRequestException(errCode, '网关超时');
          case 505:
            return BadRequestException(errCode, '不支持HTTP协议请求');
          default:
            return NetException(
                errCode, error.response?.statusMessage ?? '未知错误');
        }
      default:
        return NetException(-1, error.response?.statusMessage ?? '未知错误');
    }
  }
}

class BadRequestException extends NetException {
  BadRequestException(int code, String msg) : super(code, msg);
}

class UnauthorisedRequestException extends NetException {
  UnauthorisedRequestException(int code, String msg) : super(code, msg);
}
